package com.yimi.yinhepda.views.kua_yue_spotGoods

import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import com.yimi.yinhepda.R
import com.yimi.yinhepda.adapter.RecycleAdapter.KuaYuePalletBindAdapter
import com.pda.ym.base.CommonViewHolder
import com.pda.ym.base.BaseActivity
import com.pda.ym.callbacks.UICallBack
import com.yimi.yinhepda.entity.bean.KuaYueTaskDetailEntity
import com.yimi.yinhepda.entity.request.ForkliftDetailVos
import com.yimi.yinhepda.entity.request.PalletBindRequest
import com.yimi.yinhepda.entity.response.QueryUnloadDetailResponse
import com.yimi.yinhepda.event.ScanResult
import com.pda.ym.net.NetRequest
import com.pda.ym.utils.Constants
import com.pda.ym.utils.DateHelper
import com.pda.uce.commom.util.MyDialog
import com.pda.ym.utils.SoundVibratorManager
import kotlinx.android.synthetic.main.activity_kuayue_palletbind.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.*

/**
 * @author: lj
 * Date: 2020/4/20 17:00
 * Description:跨越托盘绑定
 */
class KuaYuePalletBindActivity : BaseActivity(true), CommonViewHolder.onItemCommonClickListener {

    private var mAdapter: KuaYuePalletBindAdapter? = null
    //托盘绑定数据集合
    private val mBindList = mutableListOf<KuaYueTaskDetailEntity>()
    //任务明细实体
    private var mDetailEntity: KuaYueTaskDetailEntity? = null

    override fun getPageName(): String {
        return "跨越托盘绑定界面"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_kuayue_palletbind)

        ib_back.setOnClickListener(this)
        ib_delete.setOnClickListener(this)
        btn_peopleDiff.setOnClickListener(this)
        btn_forkliftDiff.setOnClickListener(this)

        //注册事件
        EventBus.getDefault().register(this)

        //加载托盘扫描数据
        loadData()
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    override fun onClick(v: View?) {
        super.onClick(v)
        when (v?.id) {
            R.id.ib_back -> finish()
            R.id.ib_delete -> {
                //撤销
                if (mDetailEntity == null || !mDetailEntity!!.isCheck) {
                    SoundVibratorManager.playSound(2)
                    showToast("请选择一项删除！")
                    return
                }
                KuaYueSpotGoodsActivity.mDataList.forEach { detail ->
                    if (detail.outsideNo == mDetailEntity!!.outsideNo) {
                        //设置托盘为未绑定状态
                        detail.isPalletBind = 0
                        detail.childNos.forEach { child ->
                            child.isPalletBind = 0
                            mDetailEntity!!.isCheck = false
                        }
                    }
                }
                loadData()
            }
            R.id.btn_peopleDiff -> {
                //人工分货
                submitFunc(1)
            }
            R.id.btn_forkliftDiff -> {
                //叉车分货
                submitFunc(2)
            }
        }
    }

    override fun onItemClickListener(position: Int) {
        mDetailEntity = mBindList[position]
        if (mDetailEntity!!.isCheck) {
            mDetailEntity!!.isCheck = false
        } else {
            mBindList.forEach {
                it.isCheck = false
            }
            mDetailEntity!!.isCheck = true
        }
        mAdapter?.notifyDataSetChanged()
    }

    override fun onItemLongClickListener(position: Int) {
    }

    override fun handleBarCode(result: String?) {
        if (result == null) {
            SoundVibratorManager.playSound(2)
            showToast("运单号扫描失败")
        } else {
            doScan(result)
        }
    }

    private fun doScan(result: String) {

        mBindList.forEach { detail ->
            detail.childNos.forEach { child ->
                if ((child.subWaybillNo == result || child.subOutsideNo == result) && child.isPalletBind == 1) {
                    SoundVibratorManager.playSound(2)
                    MyDialog.showAlertDialog(this, "提示", "当前所扫描的标签已扫描，请扫描其它运单！($result)", "确定")
                    return
                }
            }
        }
        //发送消息处理扫描结果
        EventBus.getDefault().post(ScanResult(result, 2, 2))
    }

    /**
     * 加载托盘扫描数据
     */
    private fun loadData() {
        mBindList.clear()
        KuaYueSpotGoodsActivity.mDataList.forEach { detail ->
            if (detail.isPalletBind == 1) {
                mBindList.add(detail)
            }
        }

        if (mAdapter == null) {
            mAdapter = KuaYuePalletBindAdapter(this, mBindList, this)
            rv_list.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
            rv_list.adapter = mAdapter
        } else {
            mAdapter!!.notifyDataSetChanged()
        }
    }

    /**
     * 提交
     */
    private fun submitFunc(type: Int) {
        MyDialog.showAlertDialog(this, "确定提交？", "确定", "取消",
                { dialog, _ ->
                    dialog.dismiss()
                    //数据提交
                    requestSubmit(type)
                }, { dialog, _ -> dialog.dismiss() })
    }

    private fun requestSubmit(type: Int) {
        if (mBindList.isNullOrEmpty()) {
            showToast("无扫描数据不可提交！")
            SoundVibratorManager.playSound(2)
            return
        }
        showPgDlg("提交中...")
        val palletTaskNo = Constants.getPalletTaskNo()
        val palletBindRequest = PalletBindRequest()
        val forkliftDetailVos = mutableListOf<ForkliftDetailVos>()
        mBindList.forEach { detail ->
            if (detail.isPalletBind == 1) {
                detail.childNos.forEach { child ->
                    if (child.isPalletBind == 1) {
                        val detailVos = ForkliftDetailVos()
                        detailVos.waybillNo = child.waybillNo
                        detailVos.childWaybillNo = child.subWaybillNo
                        detailVos.areaCode = detail.areaCode
                        detailVos.nextDeptCode = detail.nextDeptCode
                        detailVos.nextDept = detail.nextDeptName
                        //PDA 输入
                        detailVos.inputType = 1
                        detailVos.forkliftNo = palletTaskNo
                        //叉车分货
                        detailVos.scanType = type
                        detailVos.cancleStatu = 1
                        detailVos.operTime = DateHelper.getDateTimeFormateForSimple(Date())
                        detailVos.bandType = 2
                        forkliftDetailVos.add(detailVos)
                    }
                }
            }
        }
        palletBindRequest.forkliftDetailVos = forkliftDetailVos

        NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setUrl(Constants.URL_BIND_FORFLIFT)
                .setRequestObject(palletBindRequest)
                .setResponsClazz(QueryUnloadDetailResponse::class.java)
                .execute(object : UICallBack() {
                    override fun onError(msg: String) {
                        dismissPgDlg()
                        showToast(msg)
                        SoundVibratorManager.playSound(2)
                    }

                    override fun onSuccess(obj: Any) {
                        dismissPgDlg()
                        SoundVibratorManager.playSound(1)
                        showToast("绑定成功")
                        KuaYueSpotGoodsActivity.mDataList.forEach { detail ->
                            //设置托盘为未绑定状态
                            detail.isPalletBind = 0
                            detail.childNos.forEach { child ->
                                child.isPalletBind = 0
                            }
                        }
                        loadData()
                    }
                })
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMainEventBus(event: ScanResult) {
        if (event.operType == 1 && event.operSource == 2) {
            //跨越卸车扫描发送的扫描信息
            loadData()
            SoundVibratorManager.playSound(1)
        }
    }
}